package question;

/**
 * @program: javase
 * @description: 两个线程交替打印到100
 * @author: lld
 * @create: 2021-06-07 19:47
 **/
public class Question3 {
    private int n = 1;//标志位

    public synchronized void printOdd(int num) throws InterruptedException {
//        判断等待
        if (n == 0) wait();
        if (num % 2 == 1) {
            System.out.println(Thread.currentThread().getName() + ": " + num);

        }
//        唤醒
        n = 0;
        notify();
    }

    public synchronized void printEven(int num) throws InterruptedException {
//        判断等待
        if (n == 1) wait();
        if (num % 2 == 0) {
            System.out.println(Thread.currentThread().getName() + ": " + num);

        }
//        唤醒
        n = 1;
        notify();
    }

    public static void main(String[] args) {
        Question3 question3 = new Question3();
        Thread t1 = new Thread(() -> {
            try {
                for (int i = 1; i <= 100; i++) {
                    question3.printEven(i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"偶数线程");

        Thread t2 = new Thread(() -> {
            try {
                for (int i = 1; i <= 100; i++) {
                    question3.printOdd(i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"奇数线程");

//
        t1.start();
        t2.start();
//        main线程最后执行
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("print finished");
    }
}
